package com.chs.recoginition.vo.auth;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


@Data
public class UserVo implements UserDetails, Serializable {
    private static final long serialVersionUID = 3641578023319451375L;

    /**
     * 用户id
     */
    private Long userId;

    /**
     * 用户名
     */
    private String username;

    /**
     * 用户姓名
     */
    private String name;

    /**
     * 密码
     */
    @JsonIgnore
    private String password;

    /**
     * 角色
     */
    private List<RoleVo> roles;

    /**
     * 资源
     */
    private List<ResourceVo> resources;

    /**
     * spring security 权限
     */
    private List<GrantedAuthority> authorityList;

    /**
     * 用户关联的菜单信息
     */
    private List<MenuVo> menuInfoList;

    /**
     * 是否禁用  1 是 0 否
     */
    private Boolean disable;

    @Override
    public String toString() {
        return "UserVo{" +
                "userId=" + userId +
                ", username='" + username + '\'' +
                ", name='" + name + '\'' +
                ", password='" + "***" + '\'' +
                ", roles=" + roles +
                ", resources=" + resources +
                ", disable=" + disable +
                '}';
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorityList == null) {
            authorityList = new ArrayList<>();
            //this.roles.forEach(role -> authorityList.add(new SimpleGrantedAuthority(role.getCode())));
            //this.resources.forEach(resource -> authorityList.add(new SimpleGrantedAuthority(resource.getCode())));
            authorityList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        }
        return authorityList;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return !disable;
    }

    /**
     * 用户是否拥有角色
     *
     * @param role 角色名称
     * @return true 拥有 | false 没有
     */
    public boolean isHasRole(String role) {
        return this.roles.stream().map(RoleVo::getCode).anyMatch(roleName -> roleName.equals(role));
    }
}
